#!/usr/bin/env bash
# 安装 OpenSSH Server / Fail2ban / UFW 菜单
set -Eeuo pipefail

type log_info >/dev/null 2>&1 || { echo "[install_ssh_fw] _common.sh 未加载"; exit 1; }

install_openssh_and_fail2ban() {
  ensure_root
  apt_quiet_update
  DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server fail2ban
  systemctl enable --now ssh
  systemctl enable --now fail2ban
  systemctl --no-pager -l status ssh || true
  systemctl --no-pager -l status fail2ban || true
  log_info "OpenSSH Server & Fail2ban 已安装并启动（开机自启）"
}

ufw_menu() {
  ensure_root
  echo "------ UFW 防火墙菜单 ------"
  echo "1) 安装并启用 UFW"
  echo "2) 放行 22/80/443 并启用"
  echo "3) 添加自定义端口（示例 54321/tcp）"
  echo "4) 禁用 UFW"
  echo "5) 查看 UFW 状态与规则"
  echo "0) 返回"
  read -rp "请选择: " a
  case "$a" in
    1)
      apt_quiet_update
      DEBIAN_FRONTEND=noninteractive apt-get install -y ufw
      ufw enable
      ufw status
      ;;
    2)
      apt_quiet_update
      DEBIAN_FRONTEND=noninteractive apt-get install -y ufw
      ufw allow 22/tcp
      ufw allow 80/tcp
      ufw allow 443/tcp
      ufw enable
      ufw status
      ;;
    3)
      apt_quiet_update
      DEBIAN_FRONTEND=noninteractive apt-get install -y ufw
      read -rp "输入端口/协议(如 54321/tcp): " p
      [ -n "$p" ] && ufw allow "$p"
      ufw status
      ;;
    4)
      DEBIAN_FRONTEND=noninteractive apt-get install -y ufw
      ufw disable
      ufw status
      ;;
    5)
      ufw status verbose
      ;;
    0) ;;
    *) echo "无效选择" ;;
  esac
}
